import React, { useState, useEffect, useCallback } from "react";
import { ProjectAPI } from "@/api/project";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from "recharts";
import {
  Calendar,
  Filter,
  AlertCircle,
  RefreshCw,
  BarChart3,
  TrendingUp,
  Zap,
  FolderKanban,
  CheckCircle,
  MapPin,
} from "lucide-react";
import {
  format,
  startOfDay,
  startOfMonth,
  startOfYear,
  endOfDay,
  endOfMonth,
  endOfYear,
  isDate,
} from "date-fns";

import CrossingPointsMap from "../components/dashboard/CrossingPointsMap";
import { DictTypeAPI, DictDataAPI } from "@/api/dictionary";

const retryApiCall = async (apiCall, maxRetries = 3, delay = 1000) => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await apiCall();
    } catch (error) {
      console.log(`API调用失败，第 ${attempt} 次尝试:`, error.message);
      if (attempt === maxRetries) {
        throw error;
      }
      await new Promise((resolve) =>
        setTimeout(resolve, delay * Math.pow(2, attempt - 1))
      );
    }
  }
};

export default function Dashboard() {
  const [projects, setProjects] = useState([]);
  const [crossingPoints, setCrossingPoints] = useState([]);
  const [schemes, setSchemes] = useState([]);
  const [filteredData, setFilteredData] = useState({
    projects: [],
    crossingPoints: [],
    schemes: [],
  });
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  // 新增跨越类型相关状态
  const [crossingTypeLabels, setCrossingTypeLabels] = useState({});
  const [isLoadingCrossingTypes, setIsLoadingCrossingTypes] = useState(true);

  const [timeFilter, setTimeFilter] = useState("all");
  const [customDateStart, setCustomDateStart] = useState("");
  const [customDateEnd, setCustomDateEnd] = useState("");

  // 加载跨越类型数据
  const loadCrossingTypeLabels = useCallback(async () => {
    try {
      setIsLoadingCrossingTypes(true);

      // 1. 调用DictTypeAPI获取"跨越类型"的字典类型信息
      const typeResponse = await DictTypeAPI.getList({ dictType: "crossingType" });

      // 获取跨越类型的dictId（从响应的rows中提取）
      const crossingType = typeResponse.rows.find(
        (item) => item.dictName === "跨越类型"
      );

      if (!crossingType?.dictId) {
        throw new Error("未找到跨越类型字典定义");
      }

      // 2. 调用DictDataAPI获取具体的字典数据
      const dataResponse = await DictDataAPI.getList({
        dictTypeId: crossingType.dictId,
      });

      // 构建类型映射表（dictValue -> dictLabel）
      const labels = {};
      dataResponse.rows.forEach((item) => {
        if (item.dictValue && item.dictLabel) {
          labels[item.dictValue] = item.dictLabel;
        }
      });

      setCrossingTypeLabels(labels);
    } catch (err) {
      console.error("加载跨越类型标签失败:", err);
      // 保留默认值作为降级方案
      setCrossingTypeLabels({});
    } finally {
      setIsLoadingCrossingTypes(false);
    }
  }, []);

  const applyFilters = useCallback(() => {
    if (!crossingPoints.length && !schemes.length && !projects.length) {
      setFilteredData({ projects: [], crossingPoints: [], schemes: [] });
      return;
    }

    let startDate, endDate;
    const now = new Date();
    let useFilter = true;

    switch (timeFilter) {
      case "today":
        startDate = startOfDay(now);
        endDate = endOfDay(now);
        break;
      case "thisMonth":
        startDate = startOfMonth(now);
        endDate = endOfMonth(now);
        break;
      case "thisYear":
        startDate = startOfYear(now);
        endDate = endOfYear(now);
        break;
      case "custom":
        if (customDateStart && customDateEnd) {
          startDate = new Date(customDateStart);
          endDate = new Date(customDateEnd);
          // 验证日期有效性
          if (!isDate(startDate) || !isDate(endDate) || startDate > endDate) {
            useFilter = false;
          }
        } else {
          useFilter = false;
        }
        break;
      default:
        useFilter = false;
        break;
    }

    // 不需要过滤时直接返回全部数据
    if (!useFilter) {
      setFilteredData({ projects, crossingPoints, schemes });
      return;
    }

    // 通用日期过滤函数
    const filterByDate = (item) => {
      if (!item.createdDate) return false;
      const itemDate = new Date(item.createdDate);
      return isDate(itemDate) && itemDate >= startDate && itemDate <= endDate;
    };

    const filteredProjects = projects.filter(filterByDate);
    const filteredCrossingPoints = crossingPoints.filter(filterByDate);
    const filteredSchemes = schemes.filter(filterByDate);

    setFilteredData({
      projects: filteredProjects,
      crossingPoints: filteredCrossingPoints,
      schemes: filteredSchemes,
    });
  }, [
    timeFilter,
    customDateStart,
    customDateEnd,
    crossingPoints,
    schemes,
    projects,
  ]);

  // 加载跨越类型数据
  useEffect(() => {
    loadCrossingTypeLabels();
  }, [loadCrossingTypeLabels]);

  useEffect(() => {
    loadDashboardData();
  }, []);

  useEffect(() => {
    applyFilters();
  }, [applyFilters]);

  const loadDashboardData = async () => {
    setIsLoading(true);
    setError(null);
    let errorMessages = [];

    try {
      const [projectsResult, crossingPointsResult, schemesResult] =
        await Promise.allSettled([
          retryApiCall(() => ProjectAPI.getList()),
          retryApiCall(() => CrossingPointAPI.getList()),
          retryApiCall(() => ConstructionSchemeAPI.getList()),
        ]);

      if (projectsResult.status === "fulfilled") {
        setProjects(
          Array.isArray(projectsResult.value.data)
            ? projectsResult.value.data
            : []
        );
      } else {
        console.error("加载项目数据失败:", projectsResult.reason);
        errorMessages.push("项目数据");
        setProjects([]);
      }

      if (crossingPointsResult.status === "fulfilled") {
        setCrossingPoints(
          Array.isArray(crossingPointsResult.value.data)
            ? crossingPointsResult.value.data
            : []
        );
      } else {
        console.error("加载跨越点数据失败:", crossingPointsResult.reason);
        errorMessages.push("跨越点数据");
        setCrossingPoints([]);
      }

      if (schemesResult.status === "fulfilled") {
        setSchemes(
          Array.isArray(schemesResult.value.data)
            ? schemesResult.value.data
            : []
        );
      } else {
        console.error("加载施工方案数据失败:", schemesResult.reason);
        errorMessages.push("施工方案数据");
        setSchemes([]);
      }

      if (errorMessages.length > 0) {
        setError(
          `部分数据加载失败: ${errorMessages.join(", ")}。请检查网络连接。`
        );
      }
    } catch (e) {
      console.error("加载仪表盘数据时发生未知错误:", e);
      setError("加载数据时发生未知错误，请重试。");
    } finally {
      setIsLoading(false);
    }
  };

  // 柱状图数据 - 只显示跨越点数量
  const getCrossingTypeStats = () => {
    const stats = {};

    filteredData.crossingPoints.forEach((point) => {
      const type = point.crossingType;
      // 使用接口获取的标签，如果没有则显示"其他"
      const label = crossingTypeLabels[type] || "其他";

      if (!stats[label]) {
        stats[label] = 0;
      }
      stats[label]++;
    });

    return Object.entries(stats).map(([type, count]) => ({
      type,
      跨越点数量: count,
    }));
  };

  const CHART_COLORS = [
    "#3B82F6",
    "#EF4444",
    "#10B981",
    "#F59E0B",
    "#8B5CF6",
    "#06B6D4",
    "#F97316",
    "#84CC16",
    "#EC4899",
  ];

  // 电压等级统计 - 合并相同电压的数据
  const getVoltageStats = () => {
    const stats = {};

    // 合并项目和方案的电压等级数据
    filteredData.projects.forEach((project) => {
      if (project.voltageLevel) {
        const voltage = project.voltageLevel.trim();
        stats[voltage] = (stats[voltage] || 0) + 1;
      }
    });

    filteredData.schemes.forEach((scheme) => {
      // 查找对应的项目获取电压等级
      const relatedProject = filteredData.projects.find(
        project => project.id === scheme.projectId
      );
      if (relatedProject && relatedProject.voltageLevel) {
        const voltage = relatedProject.voltageLevel.trim();
        stats[voltage] = (stats[voltage] || 0) + 1;
      }
    });

    return Object.entries(stats)
      .map(([voltage, count], index) => ({
        voltage: voltage || "未知",
        count,
        fill: CHART_COLORS[index % CHART_COLORS.length],
      }))
      .sort((a, b) => b.count - a.count); // 按数量降序排列
  };

  const handleRetry = () => {
    loadDashboardData();
  };

  const crossingTypeData = getCrossingTypeStats();
  const voltageData = getVoltageStats();

  return (
    <div className="p-4 md:p-6 space-y-6 bg-gray-50 min-h-screen">
      <div className="max-w-screen-2xl mx-auto">
        <Card className="mb-6">
          <CardHeader className="flex flex-col sm:flex-row justify-between items-start sm:items-center">
            <div>
              <CardTitle className="text-2xl font-bold text-gray-900">
                数据驾驶舱
              </CardTitle>
              <p className="text-gray-500 mt-1">跨越点和施工方案数据统计分析</p>
            </div>
            <div className="flex flex-wrap items-center gap-2 mt-4 sm:mt-0">
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4 text-gray-500" />
                <Select value={timeFilter} onValueChange={setTimeFilter}>
                  <SelectTrigger className="w-auto sm:w-36">
                    <SelectValue placeholder="时间范围" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部时间</SelectItem>
                    <SelectItem value="today">今日</SelectItem>
                    <SelectItem value="thisMonth">本月</SelectItem>
                    <SelectItem value="thisYear">本年</SelectItem>
                    <SelectItem value="custom">自定义</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {timeFilter === "custom" && (
                <>
                  <input
                    type="date"
                    value={customDateStart}
                    onChange={(e) => setCustomDateStart(e.target.value)}
                    className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  />
                  <input
                    type="date"
                    value={customDateEnd}
                    onChange={(e) => setCustomDateEnd(e.target.value)}
                    className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  />
                </>
              )}
              <Button
                onClick={handleRetry}
                variant="outline"
                size="icon"
                className="h-9 w-9"
              >
                <RefreshCw className="w-4 h-4" />
              </Button>
            </div>
          </CardHeader>
        </Card>

        {error && !isLoading && (
          <Alert variant="destructive" className="mb-6">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription className="flex items-center justify-between">
              <span>{error}</span>
              <Button
                variant="outline"
                size="sm"
                onClick={handleRetry}
                className="ml-4"
              >
                <RefreshCw className="w-4 h-4 mr-1" />
                重试
              </Button>
            </AlertDescription>
          </Alert>
        )}

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
          <Card className="bg-blue-500/10 border-blue-500/20">
            <CardContent className="p-4 flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-blue-600">项目总数</p>
                <p className="text-2xl font-bold text-blue-800">
                  {filteredData.projects.length}
                </p>
              </div>
              <div className="p-3 bg-blue-500/20 rounded-full">
                <FolderKanban className="w-6 h-6 text-blue-600" />
              </div>
            </CardContent>
          </Card>
          <Card className="bg-teal-500/10 border-teal-500/20">
            <CardContent className="p-4 flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-teal-600">跨越点总数</p>
                <p className="text-2xl font-bold text-teal-800">
                  {filteredData.crossingPoints.length}
                </p>
              </div>
              <div className="p-3 bg-teal-500/20 rounded-full">
                <MapPin className="w-6 h-6 text-teal-600" />
              </div>
            </CardContent>
          </Card>
          <Card className="bg-amber-500/10 border-amber-500/20">
            <CardContent className="p-4 flex items-center justify-between">
              <div>
                {" "}
                <p className="text-sm font-medium text-amber-600">施工方案数</p>
                <p className="text-2xl font-bold text-amber-800">
                  {filteredData.schemes.length}
                </p>
              </div>
              <div className="p-3 bg-amber-500/20 rounded-full">
                <TrendingUp className="w-6 h-6 text-amber-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <BarChart3 className="w-5 h-5 text-blue-600" />
                跨越类型统计
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="h-80">
                {isLoading || isLoadingCrossingTypes ? (
                  <div className="flex items-center justify-center h-full">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                  </div>
                ) : (
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={crossingTypeData}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis
                        dataKey="type"
                        textAnchor="end"
                        height={80}
                        fontSize={12}
                        angle={-45}
                      />
                      <YAxis />
                      <Tooltip />
                      <Legend />
                      <Bar
                        dataKey="跨越点数量"
                        fill="#3B82F6"
                        name="跨越点数量"
                      />
                    </BarChart>
                  </ResponsiveContainer>
                )}
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Zap className="w-5 h-5 text-yellow-600" />
                电压等级方案分布
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="h-80">
                {isLoading ? (
                  <div className="flex items-center justify-center h-full">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                  </div>
                ) : voltageData.length === 0 ? (
                  <div className="flex items-center justify-center h-full text-gray-500">
                    暂无电压等级统计数据
                  </div>
                ) : (
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={voltageData}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        label={({ voltage, count, percent }) =>
                          `${voltage}: ${count} (${(percent * 100).toFixed(
                            0
                          )}%)`
                        }
                        outerRadius={80}
                        fill="#8884d8"
                        dataKey="count"
                      >
                        {voltageData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={entry.fill} />
                        ))}
                      </Pie>
                      <Tooltip />
                    </PieChart>
                  </ResponsiveContainer>
                )}
              </div>
            </CardContent>
          </Card>
        </div>

        <Card className="overflow-hidden">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-lg">
              <MapPin className="w-5 h-5 text-blue-600" />
              跨越点地理分布
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0 h-[600px]">
            <CrossingPointsMap
              crossingPoints={filteredData.crossingPoints}
              projects={filteredData.projects}
            />
          </CardContent>
        </Card>
      </div>
    </div>
  );
}